<script setup lang="ts">
import { getEventChannel } from '@/utils'

// 选择器配置
const multiple = ref(false)
const preselected = ref<string>('')

// 数据项
interface Item {
  id: string
  name: string
  description?: string
}

// 数据列表（示例数据）
const items = ref<Item[]>([
  { id: '1', name: '选项一', description: '这是选项一的详细描述' },
  { id: '2', name: '选项二', description: '这是选项二的详细描述' },
  { id: '3', name: '选项三', description: '这是选项三的详细描述' },
  { id: '4', name: '选项四', description: '这是选项四的详细描述' },
  { id: '5', name: '选项五', description: '这是选项五的详细描述' },
])

// 已选中的项目 ID
const selectedIds = ref<string[]>([])

const channel = getEventChannel()

onLoad(() => setupEventChannel())

// 设置事件通道监听
const setupEventChannel = () => {
  try {
    // 监听初始化配置
    channel?.on('initConfig', (config: { multiple?: boolean; preselected?: string[] | string }) => {
      const { multiple: _multiple, preselected: _preselected } = config

      // 设置选择模式
      multiple.value = !!_multiple

      // 设置预选项
      if (_preselected) {
        if (Array.isArray(_preselected)) {
          // 数组形式
          selectedIds.value = _preselected
          preselected.value = _preselected.join(',') // 保存为字符串以兼容展示
        } else {
          // 字符串形式（向后兼容）
          preselected.value = _preselected
          selectedIds.value = multiple.value ? preselected.value.split(',') : [preselected.value]
        }
      }
    })
  } catch (error) {
    console.error('设置eventChannel失败:', error)
  }
}

// 处理项目选择
const handleItemSelect = (item: Item) => {
  if (!multiple.value) {
    // 单选模式：替换选中项
    selectedIds.value = [item.id]
    // 单选模式下不再自动确认，而是显示确认按钮
  } else {
    // 多选模式：切换选中状态
    const index = selectedIds.value.indexOf(item.id)
    if (index >= 0) {
      selectedIds.value.splice(index, 1)
    } else {
      selectedIds.value.push(item.id)
    }
  }
}

// 全选
const selectAll = () => {
  if (multiple.value) {
    selectedIds.value = items.value.map(item => item.id)
  }
}

// 反选
const invertSelection = () => {
  if (multiple.value) {
    const allIds = items.value.map(item => item.id)
    selectedIds.value = allIds.filter(id => !selectedIds.value.includes(id))
  }
}

// 检查项目是否被选中
const isSelected = (id: string) => {
  return selectedIds.value.includes(id)
}

// 确认选择
const confirm = () => {
  try {
    if (!multiple.value) {
      // 单选模式返回选中的项目
      const selectedItem = items.value.find(item => item.id === selectedIds.value[0])
      if (selectedItem) {
        channel?.emit('success', selectedItem)
      } else return uni.showToast({ title: '请选择一项', icon: 'none' })
    } else {
      // 多选模式返回选中的项目数组
      const selectedItems = items.value.filter(item => selectedIds.value.includes(item.id))
      if (selectedItems.length === 0)
        return uni.showToast({ title: '请至少选择一项', icon: 'none' })
      channel?.emit('success', selectedItems)
    }

    // 返回上一页
    uni.navigateBack()
  } catch (error) {
    console.error('确认选择失败:', error)
    uni.showToast({ title: '确认失败，请重试', icon: 'none' })
  }
}

// 取消选择
const cancel = () => {
  uni.navigateBack()
}
</script>

<template>
  <view class="min-h-screen bg-black text-white flex flex-col">
    <!-- 多选模式下的工具栏 -->
    <view v-if="multiple" class="p-3 border-b border-gray-800 flex justify-between">
      <text class="text-blue-400 text-sm" @click="selectAll">全选</text>
      <text class="text-blue-400 text-sm" @click="invertSelection">反选</text>
    </view>

    <!-- 选项列表 -->
    <scroll-view class="flex-1" scroll-y>
      <view class="p-4">
        <view
          v-for="item in items"
          :key="item.id"
          class="p-4 rounded-lg mb-3 flex items-center"
          :class="
            isSelected(item.id)
              ? 'bg-blue-900/30 border border-blue-500/30'
              : 'bg-gray-800 border border-gray-700'
          "
          hover-class="bg-opacity-90"
          @click="handleItemSelect(item)"
        >
          <!-- 选项信息 -->
          <view class="flex-1">
            <text class="block text-base">{{ item.name }}</text>
            <text v-if="item.description" class="block text-sm text-gray-400 mt-1">
              {{ item.description }}
            </text>
          </view>

          <!-- 选择指示器 -->
          <view
            v-if="isSelected(item.id)"
            class="ml-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center"
          >
            <text class="text-white text-xs">✓</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作区 -->
    <view class="p-4 border-t border-gray-800">
      <view class="flex gap-3">
        <button class="flex-1 bg-gray-700 text-white py-3 rounded-lg" @click="cancel">取消</button>
        <button class="flex-1 bg-blue-600 text-white py-3 rounded-lg" @click="confirm">
          {{ multiple ? `确认选择 (${selectedIds.length})` : '确认' }}
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
// 覆盖默认样式
page {
  background-color: #000;
}
</style>
